<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <style>
        .box1 table {
            margin: 30px 0;
        }

        img {
            width: 120px;
            height: 100px;
        }

        .box2 div {
            font-size: 20px;
        }

        .box2 table {
            margin: 30px 0;
        }

        .settlement {
            width: 60px;
            height: 30px;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="box1">
        <h1>商品列表</h1>
        <input type="text" class="search">
        <button class="searchbtn">搜索</button>
        <table border="1px" cellspacing=0 style="width: 1000px;">
            <thead>
                <tr>
                    <th>商品图片</th>
                    <th>商品名称</th>
                    <th>价格</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

    <div class="box2">
        <h1>购物车</h1>
        <button class="clearCar">清空购物车</button>
        <table border="1px" cellspacing=0 style="width: 1200px;">
            <thead>
                <tr>
                    <th><input type="checkbox" class="check_btn"></th>
                    <th>商品图片</th>
                    <th>商品名称</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <div>总价：￥<span>0</span></div>
        <button class="settlement">结算</button>
    </div>
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>

    <script>
        // 商品列表数据
        var goods_list = [
            {
                id: 1,
                photo: 'https://g-search3.alicdn.com/img/bao/uploaded/i4/i2/2207629895384/O1CN01wvqODw1pdvTf5wDkr_!!4611686018427381464-0-item_pic.jpg_360x360q90.jpg_.webp',
                name: '按摩椅',
                price: 20
            },
            {
                id: 2,
                photo: 'https://g-search3.alicdn.com/img/bao/uploaded/i4/i4/O1CN013JhOCR1y8cbmh7K51_!!0-paimai.jpg_360x360q90.jpg_.webp',
                name: '五粮液',
                price: 10
            },
            {
                id: 3,
                photo: 'https://g-search1.alicdn.com/img/bao/uploaded/i4/i1/2216549072286/O1CN01Bbo0Fo1Sl2NkI2oKV_!!0-item_pic.jpg_580x580q90.jpg_.webp',
                name: '手表',
                price: 40
            }
        ]

        // 购物车初始数据
        var car_list = []

        // 商品列表数据渲染
        function data() {
            $('.box1 tbody').html('')
            goods_list.forEach((item, index) => {
                $('.box1 tbody').append(
                    `<tr>
                        <th><img src="${item.photo}" alt=""></th>
                        <th>${item.name}</th>
                        <th>${item.price}</th>
                        <th><button onclick="addCar(${item.id})"}>加入购物车</button></th>
                     </tr>`)
            });

        }
        data()


        // 商品列表查找,只能找商品名字搜索
        var arr1 = []
        $('.searchbtn').click(() => {
            var rel = $('.search').val()
            $('.box1 tbody').html('')
            if (rel != '') {
                goods_list.forEach(item => {
                    if (item.name.includes(rel)) {
                        arr1.push(item)
                        $('.box1 tbody').append(
                            `<tr>
                           <th><img src="${item.photo}" alt=""></th>
                           <th>${item.name}</th>
                           <th>${item.price}</th>
                           <th><button>加入购物车</button></th>
                        </tr>`)
                        $('.search').val('')
                    }

                })
            } else {
                alert('请输入搜索内容')
            }
        })


        // 购物车渲染
        function shoppingCar() {
            $('.box2 tbody').html(``)
            car_list.forEach((item, index) => {
                $('.box2 tbody').append(`
                <tr>
                    <th><input type="checkbox" ${item.status ? 'checked' : ''} onclick="single(${item.id})"></th>
                    <th><img src="${item.photo}" alt=""></th>
                    <th>${item.name}</th>
                    <th>${item.price}</th>
                    <th>
                        <button onclick="minus(${item.id})">-</button>
                        <span>${item.number}</span>
                        <button onclick="plus(${item.id})">+</button>
                    </th>
                    <th><button onclick="delGoods(${item.id})">删除</button></th>
                </tr>
                `)
            })
        }

        // 点击按钮添加到购物车
        function addCar(id) {
            var addGoods = goods_list.find(item => item.id == id)
            var exist = car_list.some(item => item.id == addGoods.id)
            if (exist) {
                var addGoodsIndex = goods_list.findIndex(item => item.id == id)
                car_list[addGoodsIndex].number++
                shoppingCar()
            } else {
                car_list.push({
                    id: addGoods.id,
                    photo: addGoods.photo,
                    name: addGoods.name,
                    price: addGoods.price,
                    status: false,
                    number: 1
                })
                shoppingCar()
            }
        }


        // 商品数量+1
        function plus(id) {
            var plusgoods = car_list.find(item => item.id == id)
            // console.log(plusgoods);
            plusgoods.number++
            shoppingCar()
            total()
        }
        // 商品数量-1
        function minus(id) {
            var plusgoods = car_list.find(item => item.id == id)
            if (plusgoods.number > 1) {
                plusgoods.number--
                shoppingCar()
                total()
            }
        }


        // 购物车商品删除
        function delGoods(id) {
            var delIndex = car_list.findIndex(item => item.id == id)
            car_list.splice(delIndex, 1)
            // console.log(car_list);
            shoppingCar()
            total()
        }

        // 购物车清空
        $('.clearCar').on('click', () => {
            car_list = []
            shoppingCar()
            total()
        })

        // // 全选和反选
        $('.check_btn').click(function () {
            var isChecked = $(this).prop('checked');
            car_list.forEach(item => item.status = isChecked)
            shoppingCar()
            total()
        })

        // 单选框
        function single(id) {
            var choice = car_list.find(item => item.id == id)
            choice.status = event.target.checked

            // 单选框反选
            var flag = car_list.every(item => item.status == true)
            if (flag) {
                $('.check_btn').prop('checked', true)
            } else {
                $('.check_btn').prop('checked', false)
            }

            // 被选中的计算总价
            total()
        }


        // 总价
        var totalPrice = 0
        function total() {

            car_list.forEach(item => {
                if (item.status) {
                    totalPrice += item.price * item.number
                }
            })
            $('.box2 div span').html(`${totalPrice}`)
        }


        // 结算 
        $('.settlement').click(function () {
            var settleGoods = []
            car_list.forEach(item => {
                if (item.status) {
                    settleGoods.push(item)
                }
            })
            localStorage.setItem('Car', JSON.stringify(settleGoods))
            location.assign('./购物车2结算.html')
        })
    </script>
</body>

</html>